package village.rainbow.slipin.gcm;

import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.google.android.gcm.GCMRegistrar;

public class SendRegistIdToServer implements Runnable{

	private Context _context;
	
	public SendRegistIdToServer(Context context){
		_context = context;
	}
	
	public void send(){
		/**
		 * GCM Service가 이용 가능한 Device인지 체크한다.
		 * api 8(Android 2.2) 미만인 경우나 GCMService를 이용할 수 없는
		 * 디바이스의 경우 오류를 발생시키니 반드시 예외처리하도록 한다.
		 */
		try {
			GCMRegistrar.checkDevice(_context);
			new Thread(this).start();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("TEST", "This device can't use GCM");
			return;
		}
		
	}
	
	@Override
	public void run() {
		String regId = GCMRegistrar.getRegistrationId(_context);
		/**
		 * Registration Id가 없는 경우(어플리케이션 최초 설치로 발급받은 적이 없거나,
		 * 삭제 후 재설치 등 SharedPreference에 저장된 Registration Id가 없는 경우가 이에 해당한다.)
		 */
		//if(CommonUtils.isEmpty(regId)){
		if(regId.equals("")){
			/**
			 * 3.RegstrationId가 없는 경우 GCM Server로 Regsitration ID를 발급 요청한다.
			 * 발급 요청된 Registration ID는 SharedPreference에 저장된다.
			 */
			GCMRegistrar.register(_context, "454526962700");
			
		//SharedPreference에 저장된 Registration Id가 존재하는 경우
		}else{
			sendToServer(regId);	
		}
		
	}

	protected void sendToServer(String regId) {
		try{
			//HashMap<String, String> row = new HashMap<String, String>();
			
			TelephonyManager tManager = (TelephonyManager)_context.getSystemService(Context.TELEPHONY_SERVICE);
			String number = tManager.getLine1Number();
			if(number == null){
				number = tManager.getSubscriberId();
			}
			
			HttpClient client = new DefaultHttpClient();
			//HttpPost request = new HttpPost();
			//request.setURI(new URI("http://192.168.1.73:8081/GCMServerDemo/hello.do"));
			
			//String url = "http://192.168.1.73:8081/GCMServerDemo/simple";
			String url = "http://192.168.1.73:8081/GCMServerDemo/incoming.do";
			
			JSONObject obj = new JSONObject();
			//HashMap<String, String> map = new HashMap<String, String>();
			obj.put("shop_cd", "DS8000");
			obj.put("name", "김지원");
			obj.put("registration_id", regId);
			obj.put("phone_number", number);
			
			String param = obj.toString();
			param = param.replaceAll("\\{", "").replaceAll("\\}", "");
			
//			param += "shop_cd=DS800,";
//			param += "name=김지원,";
//			param += "registration_id=" + regId + "," + "phone_number=" + number;
			
			param = URLEncoder.encode(param, "UTF-8");
			url += "?" + param;
			
			HttpClient hc = client;
			HttpParams hcParams = hc.getParams();
			HttpConnectionParams.setConnectionTimeout(hcParams, 5000);
			HttpConnectionParams.setSoTimeout(hcParams, 5000);
			
			HttpGet get = new HttpGet(url);
			get.setHeader("Content-Type", "application/json");
			
			//HttpPost get = new HttpPost(url);
			//get.setEntity(new StringEntity(row.toString(), "UTF-8"));
			HttpResponse rp = null;
			rp = hc.execute(get);
			int code = rp.getStatusLine().getStatusCode();			
			final String resStr = new String(EntityUtils.toByteArray(rp.getEntity()), "UTF-8");	
			Log.i("TEST", code + " : " + resStr);					
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
}
